// HTTP 性能测试模块
// @/utils/http/PerformanceTest.ts

interface TestResult {
  name: string
  duration: number
  success: boolean
  details?: any
  error?: string
}

interface PerformanceMetrics {
  totalRequests: number
  successCount: number
  failureCount: number
  averageTime: number
  minTime: number
  maxTime: number
  throughput: number // 请求/秒
  memoryUsage?: {
    before: number
    after: number
    delta: number
  }
}

interface TestConfig {
  concurrent: number
  iterations: number
  timeout: number
  enableCache: boolean
  mockData?: any
}

export class HttpPerformanceTest {
  private results: TestResult[] = []
  private httpClient: any
  private mockServer: MockServer
  
  constructor(httpClient: any) {
    this.httpClient = httpClient
    this.mockServer = new MockServer()
  }
  
  // 运行完整性能测试套件
  async runFullTestSuite(): Promise<void> {
    console.log('🚀 开始 HTTP 性能测试套件...')
    
    // 启动模拟服务器
    await this.mockServer.start()
    
    try {
      // 1. 基础功能测试
      await this.runBasicTests()
      
      // 2. 缓存性能测试
      await this.runCacheTests()
      
      // 3. 并发测试
      await this.runConcurrencyTests()
      
      // 4. 内存泄漏测试
      await this.runMemoryTests()
      
      // 5. 错误处理测试
      await this.runErrorHandlingTests()
      
      // 生成报告
      this.generateReport()
      
    } finally {
      await this.mockServer.stop()
    }
  }
  
  // 基础功能测试
  private async runBasicTests(): Promise<void> {
    console.log('📋 运行基础功能测试...')
    
    const tests = [
      {
        name: 'GET请求基准测试',
        test: () => this.basicGetTest()
      },
      {
        name: 'POST请求基准测试', 
        test: () => this.basicPostTest()
      }
    ]
    
    for (const { name, test } of tests) {
      await this.runSingleTest(name, test)
    }
  }
  
  // 缓存性能测试
  private async runCacheTests(): Promise<void> {
    console.log('💾 运行缓存性能测试...')
    
    const tests = [
      {
        name: '缓存命中率测试',
        test: () => this.cacheHitRateTest()
      },
      {
        name: '缓存键生成性能',
        test: () => this.cacheKeyPerformanceTest()
      }
    ]
    
    for (const { name, test } of tests) {
      await this.runSingleTest(name, test)
    }
  }
  
  // 并发测试
  private async runConcurrencyTests(): Promise<void> {
    console.log('🚦 运行并发性能测试...')
    
    const concurrencyLevels = [1, 5, 10, 20]
    
    for (const concurrent of concurrencyLevels) {
      await this.runSingleTest(
        `并发测试-${concurrent}个请求`,
        () => this.concurrencyTest(concurrent)
      )
    }
  }
  
  // 内存测试
  private async runMemoryTests(): Promise<void> {
    console.log('🧠 运行内存使用测试...')
    
    const tests = [
      {
        name: '内存泄漏检测',
        test: () => this.memoryLeakTest()
      }
    ]
    
    for (const { name, test } of tests) {
      await this.runSingleTest(name, test)
    }
  }
  
  // 错误处理测试
  private async runErrorHandlingTests(): Promise<void> {
    console.log('❌ 运行错误处理测试...')
    
    const tests = [
      {
        name: '超时处理测试',
        test: () => this.timeoutTest()
      }
    ]
    
    for (const { name, test } of tests) {
      await this.runSingleTest(name, test)
    }
  }
  
  // 执行单个测试
  private async runSingleTest(name: string, testFn: () => Promise<any>): Promise<void> {
    const startTime = performance.now()
    
    try {
      const result = await testFn()
      const duration = performance.now() - startTime
      
      this.results.push({
        name,
        duration,
        success: true,
        details: result
      })
      
      console.log(`✅ ${name}: ${duration.toFixed(2)}ms`)
    } catch (error) {
      const duration = performance.now() - startTime
      
      this.results.push({
        name,
        duration,
        success: false,
        error: error instanceof Error ? error.message : String(error)
      })
      
      console.log(`❌ ${name}: 失败 (${duration.toFixed(2)}ms)`)
    }
  }
  
  // 基础GET测试
  private async basicGetTest(): Promise<PerformanceMetrics> {
    const config: TestConfig = {
      concurrent: 1,
      iterations: 50,
      timeout: 5000,
      enableCache: false
    }
    
    return this.performLoadTest('GET', config)
  }
  
  // 基础POST测试
  private async basicPostTest(): Promise<PerformanceMetrics> {
    const config: TestConfig = {
      concurrent: 1,
      iterations: 25,
      timeout: 5000,
      enableCache: false,
      mockData: { test: 'data', timestamp: Date.now() }
    }
    
    return this.performLoadTest('POST', config)
  }
  
  // 缓存命中率测试
  private async cacheHitRateTest(): Promise<any> {
    // 模拟缓存测试
    const iterations = 50
    let simulatedHits = 0
    
    const startTime = performance.now()
    
    // 模拟缓存逻辑
    for (let i = 0; i < iterations; i++) {
      await new Promise(resolve => setTimeout(resolve, 10))
      if (i > 10) simulatedHits++ // 模拟缓存命中
    }
    
    const duration = performance.now() - startTime
    const hitRate = (simulatedHits / iterations) * 100
    
    return {
      hitRate,
      cacheHits: simulatedHits,
      totalRequests: iterations,
      averageTime: duration / iterations
    }
  }
  
  // 缓存键性能测试
  private async cacheKeyPerformanceTest(): Promise<any> {
    const iterations = 1000
    const testData = {
      user: { id: 123, name: 'test' },
      params: { page: 1, size: 10, filter: 'active' }
    }
    
    const startTime = performance.now()
    
    // 模拟缓存键生成
    for (let i = 0; i < iterations; i++) {
      const cacheKey = `GET:/api/users/${i}:${JSON.stringify(testData)}`
    }
    
    const duration = performance.now() - startTime
    
    return {
      iterations,
      totalTime: duration,
      averageTime: duration / iterations,
      throughput: iterations / (duration / 1000)
    }
  }
  
  // 并发测试
  private async concurrencyTest(concurrent: number): Promise<PerformanceMetrics> {
    const config: TestConfig = {
      concurrent,
      iterations: 50,
      timeout: 10000,
      enableCache: false
    }
    
    return this.performLoadTest('GET', config)
  }
  
  // 内存泄漏测试
  private async memoryLeakTest(): Promise<any> {
    const getMemoryUsage = () => {
      if (typeof performance !== 'undefined' && (performance as any).memory) {
        return (performance as any).memory.usedJSHeapSize
      }
      return 0
    }
    
    const initialMemory = getMemoryUsage()
    
    // 模拟大量操作
    const promises = []
    for (let i = 0; i < 100; i++) {
      promises.push(new Promise(resolve => setTimeout(resolve, 10)))
    }
    
    await Promise.allSettled(promises)
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const finalMemory = getMemoryUsage()
    
    return {
      initialMemory,
      finalMemory,
      memoryDelta: finalMemory - initialMemory,
      memoryLeakDetected: (finalMemory - initialMemory) > (5 * 1024 * 1024)
    }
  }
  
  // 超时测试
  private async timeoutTest(): Promise<any> {
    const timeoutDuration = 1000
    let timeoutCount = 0
    const attempts = 5
    
    for (let i = 0; i < attempts; i++) {
      try {
        await new Promise((resolve, reject) => {
          setTimeout(() => reject(new Error('timeout')), timeoutDuration + 100)
        })
      } catch (error) {
        timeoutCount++
      }
    }
    
    return {
      timeoutCount,
      attempts,
      timeoutRate: timeoutCount / attempts
    }
  }
  
  // 执行负载测试
  private async performLoadTest(method: string, config: TestConfig): Promise<PerformanceMetrics> {
    const { concurrent, iterations, timeout, enableCache, mockData } = config
    const results: number[] = []
    let successCount = 0
    let failureCount = 0
    
    const startTime = performance.now()
    
    // 创建并发批次
    const batches = Math.ceil(iterations / concurrent)
    
    for (let batch = 0; batch < batches; batch++) {
      const promises = []
      const currentBatchSize = Math.min(concurrent, iterations - batch * concurrent)
      
      for (let i = 0; i < currentBatchSize; i++) {
        const requestStart = performance.now()
        
        const promise = this.simulateRequest(method, mockData, timeout)
          .then(() => {
            const requestEnd = performance.now()
            results.push(requestEnd - requestStart)
            successCount++
          })
          .catch(() => {
            failureCount++
          })
        
        promises.push(promise)
      }
      
      await Promise.allSettled(promises)
    }
    
    const totalTime = performance.now() - startTime
    
    return {
      totalRequests: iterations,
      successCount,
      failureCount,
      averageTime: results.length > 0 ? results.reduce((a, b) => a + b, 0) / results.length : 0,
      minTime: results.length > 0 ? Math.min(...results) : 0,
      maxTime: results.length > 0 ? Math.max(...results) : 0,
      throughput: successCount / (totalTime / 1000)
    }
  }
  
  // 模拟请求
  private async simulateRequest(method: string, data?: any, timeout?: number): Promise<any> {
    return new Promise((resolve, reject) => {
      const delay = Math.random() * 100 + 50 // 50-150ms 随机延迟
      
      setTimeout(() => {
        if (Math.random() > 0.95) { // 5% 失败率
          reject(new Error('模拟网络错误'))
        } else {
          resolve({ method, data, timestamp: Date.now() })
        }
      }, delay)
    })
  }
  
  // 生成测试报告
  private generateReport(): void {
    console.log('\n📊 === HTTP 性能测试报告 ===')
    console.log(`测试时间: ${new Date().toLocaleString()}`)
    console.log(`总测试数: ${this.results.length}`)
    
    const successCount = this.results.filter(r => r.success).length
    const failureCount = this.results.filter(r => r.success === false).length
    
    console.log(`成功: ${successCount} | 失败: ${failureCount}`)
    console.log(`成功率: ${((successCount / this.results.length) * 100).toFixed(2)}%`)
    
    // 按类别分组显示
    const categories = this.groupByCategory()
    
    Object.entries(categories).forEach(([category, tests]) => {
      console.log(`\n📂 ${category}:`)
      tests.forEach(test => {
        const status = test.success ? '✅' : '❌'
        const time = test.duration.toFixed(2)
        console.log(`  ${status} ${test.name}: ${time}ms`)
        
        if (test.details) {
          this.logTestDetails(test.details)
        }
        
        if (test.error) {
          console.log(`    错误: ${test.error}`)
        }
      })
    })
    
    // 性能建议
    this.generatePerformanceRecommendations()
  }
  
  // 按类别分组
  private groupByCategory(): Record<string, TestResult[]> {
    const categories: Record<string, TestResult[]> = {}
    
    this.results.forEach(result => {
      let category = '其他'
      
      if (result.name.includes('基准')) category = '基础功能'
      else if (result.name.includes('缓存')) category = '缓存性能'
      else if (result.name.includes('并发')) category = '并发性能'
      else if (result.name.includes('内存')) category = '内存管理'
      else if (result.name.includes('超时')) category = '错误处理'
      
      if (!categories[category]) {
        categories[category] = []
      }
      categories[category].push(result)
    })
    
    return categories
  }
  
  // 输出测试详情
  private logTestDetails(details: any): void {
    if (details.averageTime) {
      console.log(`    平均响应时间: ${details.averageTime.toFixed(2)}ms`)
    }
    if (details.throughput) {
      console.log(`    吞吐量: ${details.throughput.toFixed(2)} 请求/秒`)
    }
    if (details.hitRate !== undefined) {
      console.log(`    缓存命中率: ${details.hitRate.toFixed(2)}%`)
    }
    if (details.memoryDelta !== undefined) {
      console.log(`    内存变化: ${(details.memoryDelta / 1024 / 1024).toFixed(2)}MB`)
    }
  }
  
  // 生成性能建议
  private generatePerformanceRecommendations(): void {
    console.log('\n💡 性能优化建议:')
    
    const slowTests = this.results.filter(r => r.success && r.duration > 1000)
    if (slowTests.length > 0) {
      console.log('⚠️  检测到响应时间较慢的测试，建议优化请求逻辑')
    }
    
    const failedTests = this.results.filter(r => !r.success)
    if (failedTests.length > 0) {
      console.log('❌ 存在失败的测试，建议检查错误处理机制')
    }
    
    console.log('✅ 建议定期运行此测试套件以监控性能变化')
  }
}

// 模拟服务器类
class MockServer {
  async start(): Promise<void> {
    console.log('🔧 启动模拟服务器...')
  }
  
  async stop(): Promise<void> {
    console.log('🔧 停止模拟服务器...')
  }
}

// 使用示例函数
export async function runHttpPerformanceTest(httpClient: any): Promise<void> {
  const tester = new HttpPerformanceTest(httpClient)
  await tester.runFullTestSuite()
}

// 快速测试函数
export async function quickPerformanceTest(httpClient: any): Promise<void> {
  console.log('⚡ 运行快速性能测试...')
  
  const tester = new HttpPerformanceTest(httpClient)
  
  // 只运行核心测试
  await tester['runBasicTests']()
  await tester['runCacheTests']()
  
  console.log('✅ 快速性能测试完成')
} 